package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Category;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.entity.Setmeal;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class DishServiceImpl implements DishService {

    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private FlavorMapper flavorMapper;
    @Autowired
    private CategoryMapper categoryMapper;
    @Autowired
    private SetmealDishMapper setmealDishMapper;
    @Autowired
    private SetmealMapper setmealMapper;


    @Override
    @Transactional
    public void saveWithFlavor(DishDTO dto) {
        //向菜品表添加数据
        Dish dish = new Dish();
        BeanUtils.copyProperties(dto, dish);
        dishMapper.insert(dish);
        //获取insert语句获取主键值 重点在mapper中
        Long id = dish.getId();
        //向口味表添加多条
        List<DishFlavor> flavors = dto.getFlavors();
        if(flavors!=null&&flavors.size() > 0){
            flavors.forEach(dishFlavor -> dishFlavor.setDishId(id));
            flavorMapper.batchInsert(flavors);
        }
    }

    @Override
    public PageResult pageQuery(DishPageQueryDTO dishPageQueryDTO) {
        PageHelper.startPage(dishPageQueryDTO.getPage(), dishPageQueryDTO.getPageSize());
        Page<DishVO> page = dishMapper.pageQuery(dishPageQueryDTO);
        long total = page.getTotal();
        List<DishVO> result = page.getResult();
        result.forEach(DishVO->{
            Long categoryId = DishVO.getCategoryId();
            Category category = categoryMapper.getCategoryById(categoryId);
            DishVO.setCategoryName(category.getName());
                }
        );
        return new PageResult(total,result);
    }

    @Override
    @Transactional
    public void batchDelete(List<Long> ids) {
        //当前菜品是否能够删除
        for(Long id:ids){
            Dish dish= dishMapper.getDishById(id);
            if(dish!=null){
                //是否起售中
                Integer status = dish.getStatus();
                if(status == StatusConstant.ENABLE){
                    throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
                }
                //当前菜品被套餐关联 不能删除
                Long num = setmealDishMapper.getSetmealCount(id);
                if(num > 0 ){
                    throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
                }
                //可以删除 还要将口味删除
                flavorMapper.deleteFlavorByDishId(id);
                dishMapper.delete(id);
            }
        }
        //dishMapper.batchDelete(ids);
    }

    @Override
    public void updateDish(DishDTO dishDTO) {
        Long id = dishDTO.getId();
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);
        dishMapper.update(dish);
        flavorMapper.deleteFlavorByDishId(id);
        List<DishFlavor> flavors = dishDTO.getFlavors();
        if(flavors!=null&&flavors.size() > 0){
            flavors.forEach(dishFlavor -> dishFlavor.setDishId(id));
            flavorMapper.batchInsert(flavors);
        }

    }

    @Override
    public DishVO getDishById(Long id) {
        DishVO dishVO = new DishVO();
        Dish dish = dishMapper.getDishById(id);
        BeanUtils.copyProperties(dish, dishVO);
        Category category = categoryMapper.getCategoryById(dish.getCategoryId());
        dishVO.setCategoryName(category.getName());
        List<DishFlavor> dishFlavors= flavorMapper.getFlavorByDishId(id);
        dishVO.setFlavors(dishFlavors);
        return dishVO;
    }

    @Override
    public void changeStatus(Integer status, Long id) {
        Dish dish = Dish.builder().status(status).id(id).build();
        dishMapper.update(dish);
        if (status == StatusConstant.DISABLE) {
            // 如果是停售操作，还需要将包含当前菜品的套餐也停售
            List<Long> dishIds = new ArrayList<>();
            dishIds.add(id);
            // select setmeal_id from setmeal_dish where dish_id in (?,?,?)
            List<Long> setmealIds = setmealDishMapper.getSetmealIdsByDishIds(dishIds);
            if (setmealIds != null && setmealIds.size() > 0) {
                for (Long setmealId : setmealIds) {
                    Setmeal setmeal = Setmeal.builder()
                            .id(setmealId)
                            .status(StatusConstant.DISABLE)
                            .build();
                    setmealMapper.update(setmeal);
                }
            }
        }
    }

    @Override
    public List<Dish> list(Long categoryId) {
        Dish dish = Dish.builder()
                .categoryId(categoryId)
                .status(StatusConstant.ENABLE)
                .build();
        List<Dish> dishList= dishMapper.list(dish);
        return dishList;
    }

    /**
     * 条件查询菜品和口味
     * @param dish
     * @return
     */
    public List<DishVO> listWithFlavor(Dish dish) {
        List<Dish> dishList = dishMapper.list(dish);

        List<DishVO> dishVOList = new ArrayList<>();

        for (Dish d : dishList) {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(d,dishVO);

            //根据菜品id查询对应的口味
            List<DishFlavor> flavors = flavorMapper.getFlavorByDishId(d.getId());

            dishVO.setFlavors(flavors);
            dishVOList.add(dishVO);
        }

        return dishVOList;
    }
}
